package com.tsunami.auth.service.auth.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsunami.auth.mapper.RoleAuthorityMapper;
import com.tsunami.auth.service.auth.IResourceService;
import com.tsunami.auth.service.auth.IRoleAuthorityService;
import com.tsunami.auth.service.auth.IUserRoleService;
import com.tsunami.authority.dto.auth.RoleAuthorityQueryDTO;
import com.tsunami.authority.dto.auth.RoleAuthoritySaveDTO;
import com.tsunami.authority.dto.auth.UserRoleSaveDTO;
import com.tsunami.authority.entity.auth.RoleAuthority;
import com.tsunami.authority.entity.auth.UserRole;
import com.tsunami.authority.enums.auth.AuthorizeType;
import com.tsunami.base.R;
import com.tsunami.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色权限关系表 服务实现类
 * </p>
 *
 * @author lx
 * @since 2021-09-23
 */
@Service
public class RoleAuthorityServiceImpl extends ServiceImpl<RoleAuthorityMapper, RoleAuthority> implements IRoleAuthorityService {

    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IResourceService resourceService;

    @Override
    public boolean saveUserRole(UserRoleSaveDTO userRole) {
        QueryWrapper param = new QueryWrapper();
        param.eq("role_id",userRole.getRoleId());
        userRoleService.remove(param);
        List<Long> userIdList = new ArrayList<>();
        String[] ids = userRole.getUserIdList().split(",");
        for (String id:ids) {
            userIdList.add(Long.valueOf(id));
        }
        List<UserRole> list = userIdList
                .stream()
                .map((userId)-> UserRole.builder()
                .userId(userId)
                .roleId(userRole.getRoleId())
                .build()).collect(Collectors.toList());
        userRoleService.saveBatch(list);
        return true;
    }

    @Override
    public boolean saveRoleAuthority(RoleAuthoritySaveDTO roleAuthoritySaveDTO) {
        QueryWrapper param = new QueryWrapper();
        param.eq("role_id",roleAuthoritySaveDTO.getRoleId());
        super.remove(param);
        List<RoleAuthority> list = new ArrayList<>();
        if(roleAuthoritySaveDTO.getResourceIdList()!=null&&roleAuthoritySaveDTO.getResourceIdList().size()>0){
            List<Long> menuIdList = resourceService.findMenuIdByResourceId(roleAuthoritySaveDTO.getResourceIdList());
            if(roleAuthoritySaveDTO.getMenuIdList()==null||roleAuthoritySaveDTO.getMenuIdList().isEmpty()){
                roleAuthoritySaveDTO.setMenuIdList(menuIdList);
            }else{
                roleAuthoritySaveDTO.getMenuIdList().addAll(menuIdList);
            }
            //保存授予的资源
            List<RoleAuthority> resourceList = new HashSet<>(roleAuthoritySaveDTO.getResourceIdList())
                    .stream()
                    .map((resourceId) -> RoleAuthority.builder()
                    .authorityType(AuthorizeType.RESOURCE)
                    .authorityId(resourceId)
                    .roleId(roleAuthoritySaveDTO.getRoleId())
                    .build()).collect(Collectors.toList());
            list.addAll(resourceList);
        }
        if(roleAuthoritySaveDTO.getMenuIdList()!=null&&roleAuthoritySaveDTO.getMenuIdList().size()>0){
            //保存授予的菜单
            List<RoleAuthority> menuList = new HashSet<>(roleAuthoritySaveDTO.getMenuIdList())
                    .stream()
                    .map((menuId)->RoleAuthority.builder()
                    .authorityType(AuthorizeType.MENU)
                    .authorityId(menuId)
                    .roleId(roleAuthoritySaveDTO.getRoleId())
                    .build()).collect(Collectors.toList());
            list.addAll(menuList);
        }
        super.saveBatch(list);
        //清理缓存中的权限和菜单
        return true;
    }

    @Override
    public R selectPageList(Long roleId) {
        Page<RoleAuthority> pages = baseMapper.selectPageList(PageUtils.buildPage(),roleId);
        return R.ok().data(pages);
    }

    @Override
    public RoleAuthorityQueryDTO authority(Long roleId) {
        QueryWrapper param = new QueryWrapper();
        param.eq("role_id",roleId);
        param.eq("authority_type",AuthorizeType.MENU);
        List<RoleAuthority> menuList = list(param);
        List<Long> menuLong = menuList.stream().map(RoleAuthority::getAuthorityId).collect(Collectors.toList());
        QueryWrapper param2 = new QueryWrapper();
        param.eq("role_id",roleId);
        param.eq("authority_type",AuthorizeType.RESOURCE);
        List<RoleAuthority> resourceList = list(param2);
        List<Long> resourceLong = resourceList.stream().map(RoleAuthority::getAuthorityId).collect(Collectors.toList());
        RoleAuthorityQueryDTO roleAuthorityQueryDTO = new RoleAuthorityQueryDTO();
        roleAuthorityQueryDTO.setRoleId(roleId);
        roleAuthorityQueryDTO.setMenuIdList(menuLong);
        roleAuthorityQueryDTO.setResourceIdList(resourceLong);
        return roleAuthorityQueryDTO;
    }
}
